<!--
 * @Description: 批次关联配置
-->
<template>
  <BaseMainSlot>
    <template v-slot:btn-box>
      <SelectButton :buttonselectlist="buttonselectlist" @nowselectbuttonindex="batchstaumet" />
      <ActionBar
        :page-no="41"
        :add-active="addActive"
        :del-active="delActive"
        :edit-active="editActive"
        :cancel-active="cancelActive"
        :save-active="saveActive"
        :has-edit="false"
        :has-save="false"
        :has-cancel="false"
        @add="add"
        @cancel="cancel"
        @edit="edit"
        @del="del"
        @save="save"
      />
    </template>
    <template v-slot:search-box>
      <SearchForm :formConfig="formConfig" :formData="searchlist" @search="search"></SearchForm>
    </template>
    <template v-slot:table-box>
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        border
        height="calc(100% - 50px)"
        @selection-change="handleSelectionChange"
        @sort-change="changeTableSort"
      >
        <el-table-column type="selection" width="55" :selectable="row => { return !row.indflag }" />
        <el-table-column type="index" label="序号" width="100" />
        <el-table-column prop="batchName" label="批次名称" />
        <el-table-column prop="batchName" label="时间段">
          <template slot-scope="scope">
            {{ scope.row.startTime }}
            <span v-if="scope.row.startTime&&scope.row.endTime">~</span>
            {{ scope.row.endTime }}
          </template>
        </el-table-column>
        <el-table-column width="120" label="操作">
          <template v-if="scope.row.batchMapperId" slot-scope="scope">
            <el-button v-if="judgePermission(41,'edit')" class="text-btn-cursor" type="text" size="small" @click="handleEdit(scope.row)"><i class="el-icon-edit-outline"></i> 修改</el-button>
            <el-button v-if="judgePermission(41,'delete')" class="text-btn-cursor cursor-delete" type="text" size="small" @click="handleDelete(scope.row)"><i class="el-icon-delete"></i> 删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <Pagination
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
    </template>
    <template v-slot:dialog>
      <el-dialog
        :title="dialogTitle + '批次关联信息'"
        :visible.sync="dialogFormVisible"
        :before-close="cancel"
        width="40%"
      >
        <el-form
          ref="formData"
          label-position="left"
          :model="formData"
          class="el-form"
        >
          <el-form-item label="批次选择:" prop="batchNo" class="w50p">
            <el-select v-model="formData.batchNo" :placeholder="formData.batchName" filterable clearable>
              <el-option v-for="(item,index) in batchList" :key="index" :label="item.batchName" :value="item.batchNo" />
            </el-select>
          </el-form-item>
          <el-form-item label="摄像头:" prop="batchName" class="w50p">
            <el-select v-model="formData.cameraId" :placeholder="formData.cameraName" clearable>
              <el-option
                v-for="(item,index) in cameraList"
                :key="index"
                :label="item.cameraName"
                :value="item.cameraId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="时间段:" prop="batchName" class="w100p">
            <el-date-picker
              v-model="datelist"
              type="datetimerange"
              :picker-options="pickerOptions"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel('formData')">
            取 消
          </el-button>
          <el-button class="zh-button-two" type="primary" @click="save('formData')">
            保 存
          </el-button>
        </div>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>

<script>
import SearchForm from '@/components/searchForm';
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import nowpagereq from "@/api/digital-production/growth-record-management/batch-association-configuration/index";
import nowpagereqone from "@/api/digital-production/growth-record-management/growth-record-managementtwo";
// import nowpagereqtwo from "@/api/system-settings/environmental-data-test-record/index";
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot"
import SelectButton from "@/components/selectbutton/index.vue";
import { mymixin } from "@/utils/mixin"
import nowpagereqthree from "@/api/basic-info-manage/camera-management/index";
import { getToken } from '@/utils/auth';
import { mapGetters } from 'vuex';
// import { getToken } from '@/utils/auth';
export default {
  name: "BatchAssociationConfiguration",
  components: { SearchForm, ActionBar, Pagination, BaseMainSlot, SelectButton },
  mixins: [mymixin],
  data() {
    return {
      formConfig: [
        {
          label: '批次选择',
          prop: 'batchNo',
          type: 'select',
          options: [], // batchList
          optionKey: { label: 'batchName', value: 'batchNo' },
        }
      ],
      searchlist: {},
      buttonselectlist: [{ name: "未完成" }, { name: "已完成" }],
      status: 0,
      datelist: [],
      // cameramessage: {},
      cameraList: [],
      // 可选择批次列表
      batchList: [],
      // 一般为农业类型id
      farmingTypeNo: "",
      // 所搜索框内容
      searchList: {},
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      dialogTitle: null,
      dialogFormVisible: null
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    })
  },
  watch: {
    nowChanceStau(newval) {
      this.getselectdatalist();
      // this.nowplantTypeName = "种养类别"
      // if (newval === "add") {
      //   this.formData.batchNo = this.addcode
      // }
    }
  },
  created() {
  },
  mounted() {
    this.getselectdatalist()
    this.getTableDataList()
  },
  methods: {
    // 生产批次查询
    batchstaumet(i) {
      this.status = i;
      this.getselectdatalist();
      this.search();
    },
    // 获取下拉框数据
    getselectdatalist() {
      // 获取所有批次
      nowpagereqone.getallbatchList({
        status: this.status,
      }).then(
        res => {
          this.batchList = res.data
          this.formConfig[0].options = res.data;
        }
      )
      // 获取地块
      nowpagereqthree.getcameralist().then(
        res => {
          this.cameraList = res.data;
        }
      )
    },
    // 表格查询
    getTableDataList() {
      this.loading = true;
      this.tableData = []
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        sortList: this.sortList || [],
        entity: {
          status: this.status,
          farmingTypeNo: getToken("farmingTypeNo"),
          organizationNo: getToken('organizationNo'),
          batchNo: this.searchList?.batchNo
        }
      };
      nowpagereq.getlist(params).then(res => {
        this.loading = false;
        if (res.code === 1) {
          // this.$message.success('查询成功')
        } else {
          this.$message.error('查询失败')
        }
        let data = res.data.content;
        // 赋值总条数
        this.totalSize = res.data.totalElements;
        // 赋值数组
        this.tableData = data;
        this.addblankmet()
        this.resetActionBar();
      });
      // 判断搜索输入框数据
    },
    search(searchList) {
      this.searchList = searchList
      this.currentPage = 1;
      this.getTableDataList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },
    add() {
      this.addActive = false;
      this.openDialog('add');
      this.formData = {};
      this.datelist = [];
    },
    handleEdit(rowone) {
      let row = JSON.parse(JSON.stringify(rowone))
      // if (row.indflag) {
      //   this.$message.warning("请勿选择空数据")
      //   return
      // }
      // console.log(rowone)
      // this.cameramessage = {}
      this.formData = JSON.parse(JSON.stringify(rowone));
      this.datelist = []
      this.datelist.push(row.startTime)
      this.datelist.push(row.endTime)
      this.openDialog('edit')
    },
    handleSelectionChange(list) {
      this.nowSelectList = [];
      let notvalue = true
      // console.log(list)
      this.nowSelectList = list.map(item => {
        if (item.batchMapperId) {
          return item.batchMapperId
        } else {
          notvalue = false
          return ""
        }
      });
      if (notvalue === false) {
        this.$message.warning("不可选择空数据！");
        return
      }
      if (this.nowSelectList.length >= 1) this.delActive = true;
      else this.delActive = false;
    },
    // 取消
    cancel() {
      this.addActive = true;
      this.formData = {}
      // this.cameramessage = {}
      this.datelist = []
      this.closeDialog();
    },
    // 删除时触发方法
    delmessage() {
      nowpagereq.dellist(this.nowSelectList).then(
        res => {
          if (res.code === 1) {
            this.$message.success("删除成功！");
            this.getTableDataList();
          } else {
            this.$message.error("删除失败！");
          }
        }
      )
    },
    handleDelete(data) {
      // nowpagereq.dellist([data.batchMapperId]).then(
      //   res => {
      //     if (res.code === 1) {
      //       this.$message.success("删除成功！");
      //       this.getTableDataList();
      //     } else {
      //       this.$message.error("删除失败！");
      //     }
      //   }
      // )
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass"
      })
        .then(() => {
          nowpagereq.dellist([data.batchMapperId]).then(res => {
            if (res.code === 1) {
              this.$message.success("删除成功");
              this.getTableDataList();
            } else {
              this.$message.error("删除失败");
            }
          });
        })
        .catch(() => {
          //
          this.$message("取消删除");
        });
    },
    async save() {
      // -----保存状态判断-----
      if (this.nowChanceStau === 'edit') {
        let editparams = {
          ...this.formData
        }
        // editparams.batchNo = editparams.batchMapperId
        // delete editparams.batchName
        // delete editparams.batchMapperId
        // if (this.cameramessage.value) {
        //   editparams.cameraName = this.cameramessage.name
        //   editparams.cameraId = this.cameramessage.value
        // }

        if (this.datelist[0]) {
          editparams.startTime = this.dateToFormat(this.datelist[0])
          editparams.endTime = this.dateToFormat(this.datelist[1])
        }
        nowpagereq.editlist(editparams).then(res => {
          if (res.code === 1) {
            this.$message.success("修改成功！");
            this.closeDialog();
            this.getTableDataList();
          } else {
            this.$message.error("修改失败！");
          }
        });
      } else if (this.nowChanceStau === 'add') {
        // 新增接口
        let addparams = {
          ...this.formData
        }
        if (addparams.batchNo) {
          this.batchList.forEach(
            item => {
              if (item.batchNo === addparams.batchNo) {
                addparams.organizationNo = item.organizationNo
              }
            }
          )
        }
        // if (this.cameramessage.value) {
        //   addparams.cameraName = this.cameramessage.name
        //   addparams.cameraId = this.cameramessage.value
        // }
        // eslint-disable-next-line no-return-assign
        let obj = this.batchList.find(item => item.batchNo = this.formData.batchNo);
        if (obj) addparams.batchName = obj.batchName
        if (this.datelist[0]) {
          addparams.startTime = this.dateToFormat(this.datelist[0])
          addparams.endTime = this.dateToFormat(this.datelist[1])
        }
        nowpagereq.addlist(addparams).then(res => {
          if (res.code === 1) {
            this.$message.success("添加成功！");
            this.closeDialog();
            this.getTableDataList();
          } else {
            this.$message.error("添加失败！");
          }
        });
      }
    },
    openDialog(type) {
      this.dialogFormVisible = true;
      this.dialogTitle = type === 'add' ? '新增' : '编辑'
      this.nowChanceStau = type;
    },
    closeDialog() {
      this.dialogFormVisible = false;
      this.dialogTitle = null;
      this.nowChanceStau = '';
    }
  }
};
</script>

<style scoped lang="scss">
.w100p{
  :deep(.el-range-input){
    color: #000 !important;
  }
}
::v-deep {
  .el-range-input {
    color: #000 !important;
  }
  .el-range-separator {
    color: #000 !important;
  }
}
::v-deep .tab-select {
  width: 100%;
  .butt-list-sty {
    position: absolute;
    left: 5px;
    top: 7px;
  }
}
</style>
